import request from '@/utils/request/doRequest'
import authority from '@/utils/authority'
import { getCurrentOptions, getCurrentUrl } from '@/utils'

// code 换取 session_key
async function fetchSessionKey(code) {
  const { session_key, unionid, token, openid = '', user = {} } = await request(
    {
      url: '/api/app/v1/miniapp/session',
      method: 'post',
      data: { code }
    }
  )
  user.session_key = session_key
  user.unionid = unionid
  user.openid = openid
  authority.set(user)
  if (token) {
    user.token = token
    authority.set(user)
    const { back } = getCurrentOptions()
    if (!back) return
    wx.reLaunch({
      url: decodeURIComponent(back)
    })
  } else {
    const back = getCurrentUrl()
    // 重定向对路页面
    if (!back.startsWith('/pages/login/main')) {
      wx.redirectTo({
        url: `/pages/login/main?back=${encodeURIComponent(back)}`
      })
    }
    authority.set({ session_key, unionid })
  }
  return true
}

export default () => {
  return new Promise((resolve, reject) => {
    const user = authority.get() || {}
    if (user.token) return resolve(user) // todo
    const errorHandle = e => {
      console.error(e)
      wx.showToast({
        title: e.message || '获取code失败',
        icon: 'none'
      })
      reject(e)
    }
    wx.login({
      success({ code }) {
        fetchSessionKey(code)
          .then(resolve)
          .catch(errorHandle)
      },
      fail(e) {
        errorHandle(e)
      }
    })
  })
}
